package com.xbts.system.module.payment.kit.plugin.wallet;

import com.xbts.common.core.domain.AjaxResult;
import com.xbts.system.module.payment.domain.RefundLog;
import com.xbts.system.module.payment.kit.CashierSupport;
import com.xbts.system.module.payment.kit.Payment;
import com.xbts.system.module.payment.kit.dto.PayParam;
import com.xbts.system.module.payment.kit.params.dto.CashierParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * WalletPlugin
 *
 * @author Chopper
 * @version v1.0
 * 2021-02-20 10:14
 */
@Slf4j
@Component
public class WalletPlugin implements Payment {

    /**
     * 收银台
     */
    @Autowired
    private CashierSupport cashierSupport;


    @Override
    public AjaxResult h5pay(HttpServletRequest request, HttpServletResponse response, PayParam payParam) {
        savePaymentLog(payParam);
        return AjaxResult.success("支付成功");
    }

    @Override
    public AjaxResult jsApiPay(HttpServletRequest request, PayParam payParam) {
        savePaymentLog(payParam);
        return AjaxResult.success("支付成功");
    }

    @Override
    public AjaxResult appPay(HttpServletRequest request, PayParam payParam) {
        savePaymentLog(payParam);
        return AjaxResult.success("支付成功");
    }

    @Override
    public AjaxResult nativePay(HttpServletRequest request, PayParam payParam) {
        return AjaxResult.success("支付成功");
    }

    @Override
    public AjaxResult mpPay(HttpServletRequest request, PayParam payParam) {
        savePaymentLog(payParam);
        return AjaxResult.success("支付成功");
    }

    /**
     * 保存支付日志
     *
     * @param payParam 支付参数
     */
    private void savePaymentLog(PayParam payParam) {
        //同一个会员如果在不同的客户端使用预存款支付，会存在同时支付，无法保证预存款的正确性，所以对会员加锁
//        RLock lock = redisson.getLock(UserContext.getCurrentUser().getId() + "");
//        lock.lock();
        try {
            //获取支付收银参数
            CashierParam cashierParam = cashierSupport.cashierParam(payParam);
            this.callBack(payParam, cashierParam);
        } finally {
//            lock.unlock();
        }
    }

    @Override
    public void refund(RefundLog refundLog) {
        // TODO 余额退款
    }

    /**
     * 支付订单
     *
     * @param payParam     支付参数
     * @param cashierParam 收银台参数
     */
    public void callBack(PayParam payParam, CashierParam cashierParam) {
        // 余额支付回调

    }

}
